package com.supermarket_project.service.impl;

import com.supermarket_project.common.R;
import com.supermarket_project.mapper.LoadingMapper;
import com.supermarket_project.pojo.Loading;
import com.supermarket_project.service.LoadingService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class LoadingServiceImpl implements LoadingService {
    @Autowired
    private LoadingMapper loadingMapper;

    //获取sql.util.timestamp
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    Date date = new Date();
    Timestamp timestamp = new Timestamp(date.getTime());

    /**
     * 上货，同时增加商品库存数量
     * @param data
     * @return R
     */
    @Override
    public R insertLoading_s(List<Map> data) {
        R r = new R();
        try{

            //上货表插入状态
            int[] insertRes = new int[data.size()];
            //商品表更新状态
            int[] updateGoodsRes = new int[data.size()];
            //商品表更新信息
            ArrayList<String> updateMsgList = new ArrayList<>();
            for (int i=0;i<data.size();i++){
                //List每个人元素新建一个pojo实体（Loading）
                Loading loading = new Loading();
                //给临时实体loading属性赋值
                loading = setLoading(loading,data,i);

                //MyBatis插入和更新返回数据类型为int，成功为1
                if (loadingMapper.increaseGoodsQuantity_m(loading)==1){
                    updateGoodsRes[i] = 1;
                    //上货表插入上货记录
                    insertRes[i] = loadingMapper.insertLoading_m(loading);
                }else {
                    updateGoodsRes[i] = 0;
                    updateMsgList.add("流水号："+loading.getSerial_number()+"，"+loading.getLoad_goods_name()+"上货不成功，请检查该商品的锁定状态或删除状态!");
                }
            }
            updateMsgList.trimToSize();
            updateMsgList.sort(Comparator.naturalOrder());
            r.setData(updateMsgList);
            //判断上货表多条数据是否插入和更新成功
            for (int i=0;i<insertRes.length;i++){
                if (insertRes[i]!=1){
                    r.setCode(501);
                    r.setMsg("上货记录插入出现异常!");
                    return r;
                }
            }
            //判断goods商品表是否更新成功
            for (int i=0;i<updateGoodsRes.length;i++){
                if (updateGoodsRes[i]!=1){
                    r.setCode(502);
                    r.setMsg("商品表更新出现异常!");
                    return r;
                }
            }
            r.setCode(200);
            r.setMsg("所有商品上货成功!");
        }catch (Exception e){
            r.setCode(500);
            r.setMsg("后端代码出现异常!");
            e.printStackTrace();
        };
        return r;
    }

    /**
     * 设置loading实体各属性
     * @param loading
     * @param data
     * @param i
     * @return Loading
     */
    public Loading setLoading(Loading loading,List<Map> data,int i) {
        loading.setSerial_number(Long.parseLong(data.get(i).get("serial_number").toString()));
        loading.setLoad_staff_id(Long.parseLong(data.get(i).get("load_staff_id").toString()));
        loading.setLoad_goods_num(data.get(i).get("load_goods_num").toString());
        loading.setLoad_goods_name(data.get(i).get("load_goods_name").toString());
        loading.setUnit(data.get(i).get("unit").toString());
        loading.setLoading_quantity(Long.parseLong(data.get(i).get("loading_quantity").toString()));
        loading.setLoad_time(timestamp);
        return loading;
    }

    /**
     * 查询最新一条流水号
     * @return
     */
    @Autowired
    public R querySerialNumber_s() {
        R r = new R();
        try {
            List<Loading> res = loadingMapper.querySerialNumber_m();
            r.setCode(200);
            r.setMsg("查询最新流水号成功");
            r.setData(res.get(0).getSerial_number());
        } catch (Exception e) {
            r.setCode(500);
            r.setMsg("查询失败，后端代码异常");
            e.printStackTrace();
        }
        return r;
    }

    /**
     * 根据条码返回商品信息（包括商品名称和单位）
     * @param barcode
     * @return
     */
    public R selectByBarcode_s(String barcode){
        System.out.println("ServiceImpl的barcode：");
        System.out.println(barcode);
        R r = new R();
        try{
            String r_goods_name = loadingMapper.selectNameByBarcode_m(barcode);
            String r_goods_unit = loadingMapper.selectUnitByBarcode_m(barcode);


            Map<String,String> rMap = new HashMap<>();
            rMap.put("load_goods_num",barcode);
            rMap.put("load_goods_name",r_goods_name);
            rMap.put("unit",r_goods_unit);
            r.setCode(200);
            r.setMsg("查询成功!");
            r.setData(rMap);
        }catch (Exception e){
            r.setCode(500);
            r.setMsg("查询失败，检查条码是否正确或者库存是否有该商品");
            e.printStackTrace();
        }
        return r;
    }

    /**
     * 根据Excel表上货
     * @param excelFile
     * @param fileName
     * @return R
     */
    public R processExcel_s(InputStream excelFile,String fileName){
        R r =new R();

        try{
            Workbook workbook = this.getWorkbook(excelFile,fileName);
            Sheet sheet = workbook.getSheetAt(0);

            //上货表插入状态
            int[] insertRes = new int[sheet.getLastRowNum()];
            //商品表更新状态
            int[] updateGoodsRes = new int[sheet.getLastRowNum()];
            //商品表更新信息
            ArrayList<String> updateMsgList = new ArrayList<>();
            int p=0;
            for (int i=1;i<= sheet.getLastRowNum();i++){
                //List每个人元素新建一个pojo实体（Loading）
                Loading loading = new Loading();
                //给临时实体loading属性赋值
                loading.setSerial_number(Long.parseLong(removeLast2Bit(sheet.getRow(i).getCell(0).toString())));
                loading.setLoad_staff_id(Long.parseLong(removeLast2Bit(sheet.getRow(i).getCell(1).toString())));
                loading.setLoad_goods_name(sheet.getRow(i).getCell(2).toString());
                loading.setLoad_goods_num(sheet.getRow(i).getCell(3).toString());
                loading.setUnit(sheet.getRow(i).getCell(4).toString());
                loading.setLoading_quantity(Long.parseLong(removeLast2Bit(sheet.getRow(i).getCell(5).toString())));
                loading.setLoad_time(timestamp);
                //MyBatis插入和更新返回数据类型为int，成功为1

                if (loadingMapper.increaseGoodsQuantity_m(loading)==1){
                    updateGoodsRes[p] = 1;
                    //上货表插入上货记录
                    insertRes[p] = loadingMapper.insertLoading_m(loading);
                }else {
                    updateGoodsRes[p++] = 0;
                    updateMsgList.add("流水号："+loading.getSerial_number()+"，"+loading.getLoad_goods_name()+"上货不成功，请检查该商品的锁定状态或删除状态!");
                }
            }
            updateMsgList.trimToSize();
            updateMsgList.sort(Comparator.naturalOrder());
            r.setData(updateMsgList);
            //判断上货表多条数据是否插入和更新成功
            for (int i=0;i<insertRes.length;i++){
                if (insertRes[i]!=1){
                    r.setCode(501);
                    r.setMsg("上货记录插入出现异常!");
                    return r;
                }
            }
            //判断goods商品表是否更新成功
            for (int i=0;i<updateGoodsRes.length;i++){
                if (updateGoodsRes[i]!=1){
                    r.setCode(502);
                    r.setMsg("商品表更新出现异常!");
                    return r;
                }
            }
            r.setCode(200);
            r.setMsg("所有商品上货成功!");
        }catch (Exception e){
            e.printStackTrace();
            r.setCode(500);
            r.setMsg("后端异常!");
        }
        return r;
    }

    /**
     * 截掉字符串后两位
     * @param string
     * @return
     */
    public String removeLast2Bit(String string){
        return string.substring(0,string.length()-2);
    }

    /**
     * 判断文件格式.xls/.xlsx
     * @param in
     * @param fileName
     * @return
     * @throws Exception
     */
    public Workbook getWorkbook(InputStream in, String fileName) throws Exception {
        Workbook workbook = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if(".xls".equals(fileType)){
            workbook = new HSSFWorkbook(in);
        }else if(".xlsx".equals(fileType)){
            workbook = new XSSFWorkbook(in);
        }else {
            throw new Exception("请上传.xls/.xlsx格式文件！");
        }
        return workbook;
    }

}
